var player;
var offset = 0; //当前页码
var limit = 10; //条数
var totals = 0; //总条数
var scroll;

// 加载会议详情
function loadMeeting(meetingid, userid, cbVideo, cbIm) {
	var params = {
		meetingId: meetingid,
		userId: userid
	};

	server.meeting.getDetailMeeting(params, function(r) {
		// 标题
		var vmHader = new Vue({
			el: "#detailHeaderData",
			data: r
		});

		// 信息
		var vmInfo = new Vue({
			el: '#meetingInfo',
			data: r
		});

		//	文件模型
		var filesDom = template('filestmp', {
			data: r
		});
		$("#detailFiles").append(filesDom);

		mui('#offCanvasSideScrollR').scroll(); //初始化滚动条

		//	文件模型
		/*var vmFiles = new Vue({
			el: "#detailFiles",
			data: r,
			methods: {
				download: function(item) {
					var btn = ['取消', '确认'];
					mui.confirm('确认下载该文档?', '下载提示', '', function(type) {
						if(type.index == '1') {
							var down = plus.downloader.createDownload(item.accessPath, {
								filename: '_documents/' + item.name
							}, function(d, status) {
								if(status == 200) {
									plus.runtime.openFile(d.filename);
									return;
								}
								mui.toast('下载失败' + status);
							});
							down.start();
						}
					}, 'div');
				}
			}
		});*/

		//	人员模型
		/*var vmAssistants = new Vue({
			el: "#detailAssistants",
			data: r
		});*/

		var assistantDom = template('assistantstmp', {
			data: r
		});
		$("#detailAssistants").append(assistantDom);

		mui('#offCanvasSideScrollL').scroll(); //初始化滚动条

		// 点赞模型
		var vmLike = new Vue({
			el: '#vm-like',
			data: r.meeting
		});

		var isLiked = r.meeting.liked;
		if(isLiked) { // 判断点赞状态
			$('#btnLike').css("color", "#007aff");
		}
		var meetid = r.meeting.id;

		//	点赞
		mui('body').on('tap', 'a#btnLike', function() {
			var waiting = plus.nativeUI.showWaiting('请稍候...', {
				back: 'close'
			});
			$("a#btnLike").addClass("mui-disabled");

			var likeObj = {
				userid: userid,
				meetingid: meetid
			}

			server.meeting.setLikes(likeObj, function(r) {
				if(r.errCode == 0) {
					var nums = Number($('#btnLike').text());
					setTimeout(function() {
						if(!isLiked) {
							isLiked = true;
							mui.toast('点赞成功');
							$('#btnLike').css("color", "#007aff");
							$('#btnLike').text(nums + 1);
						} else {
							isLiked = false;
							mui.toast('取消点赞');
							$('#btnLike').css("color", "#999");
							$('#btnLike').text(nums - 1);
						}

						$("a#btnLike").removeClass("mui-disabled");
					}, 0);
				}
				waiting.close();
			}, function() {
				mui.toast('点赞失败,请稍后重试');
			})

		});

		//	是否是录像
		if(r.meeting.status == 4) { //这是录像,禁用操作
			document.getElementById("btnpopover").style.display = 'none';
			mui('#txt-msg')[0].placeholder = '会议已结束';
			mui('#txt-msg')[0].disabled = true;
			mui('#btn-file')[0].disabled = true;
		} else {
			if(!r.isAssistant) { // 当前用户不是助理
				document.getElementById("btnpopover").style.display = 'none';
				if(r.meeting.status == 2) { // 状态为预约
					mui('#txt-msg')[0].disabled = true;
					mui('#videojs')[0].style.display = 'none';
					mui('#meetingInfo')[0].style.display = 'block';
					mui('#btn-file')[0].style.disabled = true;
				}
				if(r.meeting.status != 3 && r.meeting.status != 4) {
					mui.toast('会议还未开始，请稍后再来');
					return;
				}
			} else {
				document.getElementById("btnpopover").style.display = 'block';
				if(r.meeting.status == 2) {
					mui('#txt-msg')[0].placeholder = '会议未开始';
					mui('#txt-msg')[0].disabled = true;
					document.getElementById("eMeeting").style.display = 'none';
					mui('#btn-file')[0].disabled = true;
				}
				if(r.meeting.status == 3) {
					mui('#txt-msg')[0].placeholder = '请文明发言';
					document.getElementById("sMeeting").style.display = 'none';
				}
			}
		}
		var snap = r.meeting.status == 4 ? r.meeting.snapUrl : r.meeting.room.snapAccessUrl;

		// 回调视频代码
		cbVideo(r.meeting.status == 4, r.meeting.room.channel, snap, r.meeting.videoFilePathAccess, r.meeting.cdnOpen, r.meeting.room.cdnHls);

		// 回调IM代码
		cbIm(r.meeting.status);

	}, function(r) {
		mui.toast('获取服务器数据失败,请稍后刷新重试');
	})
}

function loadMeetingMsg(meetingid, offset, limit, type) {
	var params = {
		meetingid: meetingid,
		offset: offset,
		limit: limit
	}

	server.meeting.getMeetingMsgs(params, function(r) {
			if(r.errCode == 0) {
				totals = r.data.total; //总条数
				var plimit = (totals % 10); //取余预算
				if(totals - offset > 10) {
					offset += 10;
				} else {
					offset += plimit;
				}

				var groupshisrows = r.data.rows;

				if(groupshisrows.length > 0) {
					$.each(groupshisrows, function(index, item) {
						var user = server.meeting.getUserBy(item.fromUser);
						item.fromusername = user.name;
					});
				}

				console.log('totals:' + totals);
				//console.log('groupshisrows:' + JSON.stringify(groupshisrows));
				var msgDom = template('msghistorytemplate', {
					totalnums: totals,
					data: groupshisrows,
					meetingid: meetingid,
					offset: offset,
					limit: limit,
				});
				var typehight;
				if(type == 1) {
					$("#tempdom").append(msgDom);
					typehight = $("#tempdom").height();
					$("#tempdom").html('');
				}

				//var beforeh = $("#chat-msg").height();
				//console.log('beforeh=' + beforeh);

				$('#chat-msg').prepend(msgDom);

				//var afterh = $("#chat-msg").height();
				//console.log('afterh=' + afterh);

				mui.previewImage();
				if(type != 1) {
					scroll.reLayout(); //重新计算布局值，最大滚动的高度等等
					scroll.scrollToBottom(); //滚动到底部
				} else {
					scroll.scrollTo(0, 0 - typehight, 1000);
				}

			}
		},
		function(r) {
			mui.toast('获取服务器数据失败,请稍后刷新重试');
		})

}

// 聊天室
var IM = function() {
	var vue;
	var ws;
	var clientid = 1;
	var token = '';
	var userid = '';
	var groupid = '';

	var reConnectCount = 0; // 重连次数
	var reCounectMax = 10; // 最大重连次数

	// 显示消息
	var display = function(msg) {
		if(msg.fromuser == userid) {
			var user = server.user.getLoginUser();
			msg.fromuseravatar = user.avatarUrl;
			msg.fromusername = user.name;
		} else {
			var user = server.meeting.getUserBy(msg.fromuser);
			if(user) {
				msg.fromuseravatar = user.avatarUrl;
				msg.fromusername = user.name;
			}
		}
		var msgDom = template('msg-content', {
			item: msg
		});
		$("#chat-msg").append(msgDom);
		mui.previewImage();
		//mui('#chat-msg')[0].innerHTML = strDom;
		//vue.msgs.push(msg);

		setTimeout(function() {
			scroll.reLayout(); //重新计算布局值，最大滚动的高度等等
			scroll.scrollToBottom(100); //滚动到底部
		}, 500)

		if(player.paused()) {
			player.play();
		}
	}

	// 连接ws
	var connect = function() {

		var wsUrl = config.imServer + "?clientid=" + clientid + "&token=" + token + "&groupid=" + groupid + "&userid=" + userid;

		// 初始化连接
		ws = new WebSocket(wsUrl);

		// 连接成功时调用
		ws.onopen = function() {
			console.log('聊天室连接成功');
		};
		// 发生错误时调用
		ws.onerror = function(e) {
			mui.toast('聊天室连接错误');
		};
		// 连接关闭时调用
		ws.onclose = function(e) {
			mui.toast('聊天室连接关闭');
			reConnect();
		};

		// 收到消息时调用
		ws.onmessage = function(e) {
			var json = JSON.parse(e.data);
			if(json.ErrCode != undefined) {
				if(json.ErrCode != 0) {
					mui.toast(json.ErrMsg);
				} else {
					reConnectCount = 0;
				}
				return;
			}

			// 监听im是否结束会议。结束刷新当前页面
			if(json.type == "over") {
				mui.toast('会议已结束');
				location.reload()
				return;
			}

			display(JSON.parse(e.data));
		};
	};

	// Im重连机制
	var reConnect = function() {
		if(reConnectCount > reCounectMax - 1) {
			mui.alert('IM重连超时，请重试');
			return;
		}
		var delayTime = (reConnectCount + 1) * 2000;
		setTimeout(function() {
			reConnectCount++;
			console.log('reconnect ' + reConnectCount);
			if(ws && ws.readyState != 1) {
				connect();
			}
		}, delayTime);
	};

	// 摄像头
	var userCamera = function() {
		var camera = plus.camera.getCamera(); //获取手机摄像头对象
		var res = camera.supportedImageResolutions[0];
		var fmt = camera.supportedImageFormats[0];

		//调用拍照操作
		camera.captureImage(function(path) {
			plus.io.resolveLocalFileSystemURL(path, function(entry) {
				var filename;
				// 可通过entry对象操作上传的文件文件
				entry.file(function(file) {
					var fileReader = new plus.io.FileReader();
					//	文件名
					if(file.name.indexOf('.') > -1) {
						filename = file.name.split('.')[0];
					} else {
						filename = 'v' + new Date().getTime();
					}
				});

				var localpath = entry.toLocalURL() + "?version=" + new Date().getTime();
				var path = plus.io.convertLocalFileSystemURL(localpath); //转换为平台相对路径
				upload(localpath);
			}, function(error) {
				mui.toast('没有选择图片');
			});
		}, function(error) {
			mui.toast('拍照失败');
		}, {
			resolution: res,
			format: fmt
		})
	}

	// 相册
	var gallery = function() {
		plus.gallery.pick(function(path) {
			var filename = 'v=' + new Date().getTime();
			var localpath = plus.io.convertLocalFileSystemURL(path);
			upload(localpath);
		}, function(err) {
			mui.toast('取消选择');
			console.log('gallery errcode=' + err.code);
			console.log('gallery errmsg=' + err.message);
		}, { //文件过滤，只能筛选图片文件
			filter: 'image',
			multiple: false
		})
	}

	// 上传图片
	var upload = function(path) {
		var waiting = plus.nativeUI.showWaiting('上传中...', {
			back: 'close'
		});
		plus.zip.compressImage({
			src: path,
			dst: '_downloads/zip.jpg',
			overwrite: true,
			/*width: '800px',
			height: '900px',*/
			quality: 50
		}, function(e) {
			var uploadObj = plus.uploader.createUpload(config.getUpload, {
				method: 'post',
				priority: 100
			}, function(r, status) {
				if(status == 200) {
					var rJson = JSON.parse(r.responseText);
					if(rJson.errCode == 0) { // 上传成功，发送
						send(2, rJson.data[0].accessUrl);
					}
				} else {
					console.log("Upload failed: " + status);
				}
				waiting.close();
			});
			uploadObj.addFile(e.target, {
				key: 'filename'
			});
			uploadObj.start();
		}, function(err) {

		});

	}

	// 发送消息
	var send = function(msgtype, content) {
		var msg = {
			clientid: clientid,
			type: 'GroupChat',
			fromuser: userid,
			groupid: groupid,
			msgtype: msgtype, // 1-文本 2-图片 3-表情
			content: content
		};
		var strmsg = JSON.stringify(msg);
		if(ws && ws.readyState == 1) {
			ws.send(strmsg);
			mui('#txt-msg')[0].value = '';
			mui('#txt-msg')[0].blur();
			display(msg);
			mui('#btn-file')[0].style.display = 'block';
			mui('#btn-send')[0].style.display = 'none';

		} else {
			mui.toast("IM服务连接异常，state" + ws.readyState);
		}
	}

	//	结束会议通知im
	var noticeIm = function() {
		var msg = {
			type: 'over',
			userid: userid,
			groupid: groupid
		};
		//console.log('通知会议：' + JSON.stringify(msg))
		ws.send(JSON.stringify(msg));
	}

	// 初始化
	var init = function(_token, _groupid, _userid) {
		token = _token;
		userid = _userid;
		groupid = _groupid;

		mui('#chat-msgs').scroll(); //初始化滚动条
		mui('#offCanvasSideScrollL').scroll(); //初始化滚动条

		connect(); // 初始化ws

		// 输入框监听
		mui('#txt-msg')[0].addEventListener('input', function() {
			if(this.value) {
				mui('#btn-send')[0].style.display = 'block';
				mui('#btn-file')[0].style.display = 'none';
			} else {
				mui('#btn-file')[0].style.display = 'block';
				mui('#btn-send')[0].style.display = 'none';
			}
		});

		// 发送消息
		mui('.mui-bar').on('tap', '#btn-send', function(e) {
			e.preventDefault();
			var content = mui('#txt-msg')[0].value;
			if(!content || content == '') return;
			send(1, content);
		});

		// 发送图片
		mui('.mui-bar').on('tap', '#btn-file', function(e) {
			mui('#txt-msg')[0].blur();
			var opts = [{
				title: '拍照'
			}, {
				title: '从相册选择'
			}];
			plus.nativeUI.actionSheet({
				title: '发送图片',
				buttons: opts,
				cancel: '取消'
			}, function(opps) {
				switch(opps.index) {
					case 0:
						break;
					case 1:
						userCamera();
						break;
					case 2:
						gallery();
						break;
					default:
						break
				}
			});
		});

		// 看大图
		/*mui('#chat-msgs').on('tap', 'p img', function(e) {
			// todo
		});*/
	};

	// 禁言
	var ban = function(uid, ok) {
		var msg = JSON.stringify({
			type: 'ban',
			groupid: groupid,
			userid: uid,
			ok: ok
		});
		if(ws && ws.readyState == 1) {
			ws.send(msg);
		} else {
			mui.toast("操作失败");
		}
	}

	// 踢人
	var kickout = function(uid, ok) {
		var msg = JSON.stringify({
			type: 'kickout',
			groupid: groupid,
			userid: uid,
			ok: ok
		});
		if(ws && ws.readyState == 1) {
			ws.send(msg);
		} else {
			mui.toast("操作失败");
		}
	};

	return {
		init: init,
		ban: ban,
		kickout: kickout,
		noticeIm: noticeIm
	}
}();

// 视频
var Video = function() {
	var root = server.meeting.getNvrConfig().internetWebAddress;

	// 初始化播放器
	function initPlayer(url, img) {
		$("#videojs").attr("poster", img);
		$("#videojs").find("source").attr("src", url).attr("type", "application/x-mpegURL");
		player = videojs("videojs", {
			techOrder: ['html5'],
			controls: true,
			autoplay: true,
			ControlBar: {
				FullscreenToggle: false
			}
		}).ready(function() {
			this.on('fullscreenchange', function(e) {
				console.log('fullscreenchange');
			});
		});

		// 监听文档是否全屏
		document.addEventListener('webkitfullscreenchange', function() {
			var el = document.webkitFullscreenElement; //获取全屏元素
			if(el) {
				if(mui.os.plus) {
					plus.screen.lockOrientation('landscape'); //锁死屏幕方向为横屏
				}
			} else {
				if(mui.os.plus) {
					plus.screen.lockOrientation('portrait-primary'); //锁死屏幕方向为竖屏
				}
			}
		});
	}

	// 播放直播
	function play(channel, snap) {
		var waiting = plus.nativeUI.showWaiting('视频加载中...', {
			back: 'close'
		});
		var url = root + '/api/v1/getchannelstream?channel=' + channel + '&protocol=hls';
		$.get(url, function(data) {
			//var json = JSON.parse(data);
			var json;
			if(Object.prototype.toString.call(data) === "[object String]") {
				json = JSON.parse(data);
			} else {
				json = data;
			}
			console.log('1:' + JSON.stringify(json));
			var timeout = 10000;
			var step = 500;
			var cnt = 0;
			var videoUrl = root + json.EasyDarwin.Body.URL;

			function test() {
				cnt += step;
				$.ajax(videoUrl, {
					type: "HEAD",
					global: false,
					complete: function(xhr, ts) {
						if(cnt > timeout) {
							mui.toast("请求视频失败，请重试");
							waiting.close();
							mui.back();
							return;
						}
						//xhr.status == 0 , when cross domain request not found
						if(xhr.status == 404 || xhr.status == 0 || xhr.status != 200) {
							setTimeout(test, step);
						} else {
							waiting.close();
							initPlayer(videoUrl);

							var timerLive = setInterval(function() {
								$.get(root + "/api/v1/touchchannelstream", {
									Channel: channel,
									Protocol: 'HLS',
									Line: "local",
									From: "lan"
								}, function(data) {

								})
							}, 30000);
						}
					}
				})
			}
			test();
		});
	}

	return {
		init: function(isrecord, channel, snap, recordUrl, cdnOpen, cdnHls) {
			if(isrecord) {
				initPlayer(recordUrl, snap);
			} else {
				if(cdnOpen) {
					initPlayer(cdnHls, snap);
				} else {
					play(channel, snap);
				}
			}
		}
	};
}();

mui.plusReady(function() {

	scroll = mui('#chat-msgs').scroll();
	// 开启一直保持程序唤醒状态
	plus.device.setWakelock(true);

	mui.init({
		swipeBack: true, //启用右滑关闭功能
	});

	// 主界面和侧滑菜单界面均支持区域滚动；
	mui('#offCanvasSideScroll').scroll();
	//mui('#offCanvasContentScroll').scroll();

	// 参数
	var self = plus.webview.currentWebview();
	var meetingid = self.meetingid;
	var channel = self.channel;

	// 登陆信息
	var logininfo = server.user.getUserInfo();
	if(!logininfo) {
		mui.toast('请登陆');
		setTimeout(function() {
			mui.back();
		}, 600);
		return;
	}

	var token = logininfo.refresh_token;

	// 当前用户
	var userinfo = server.user.getLoginUser();
	if(!userinfo) {
		mui.toast('用户数据异常，请重新登陆');
		setTimeout(function() {
			mui.back();
		}, 600);
		return;
	}
	var userid = userinfo.id;

	//	会议详情操作处理
	mui('body').on('tap', '#btnpopover', function() {
		mui('#topPopover').popover('toggle');
		$(".mui-backdrop").hide();
	});

	//	开始会议
	mui('body').on('tap', 'a#sMeeting', function() {
		mui('#topPopover').popover('hide');
		mui.confirm('确认开始会议', '温馨提示', '', function(e) {
			if(e.index == 1) {
				server.meeting.setStartMeeting(channel, meetingid, function(r) {
					if(r.errCode == 0) {
						mui.toast('会议开始');
						mui('#txt-msg')[0].disabled = false;
						mui('#txt-msg')[0].placeholder = '请文明发言';
						document.getElementById("sMeeting").style.display = 'none';
						document.getElementById("eMeeting").style.display = 'block';
						mui('#btn-file')[0].disabled = false;

						var page = plus.webview.getWebviewById('tab-webview-subhome.html');
						mui.fire(page, 'myfresh');
					} else {
						mui.toast(r.errMsg);
					}
				}, function() {
					mui.toast('操作失败,请稍后重试');
				})
			}
		}, 'div');
	});

	//	结束会议
	mui('body').on('tap', 'a#eMeeting', function() {
		mui('#topPopover').popover('hide');
		mui.confirm('确认结束会议', '温馨提示', '', function(e) {
			if(e.index == 1) {
				server.meeting.setStopMeeting(channel, meetingid, function(r) {
					if(r.errCode == 0) {
						mui.toast('会议已结束');
						document.getElementById("btnpopover").style.display = 'none';
						mui('#txt-msg')[0].placeholder = '会议已结束';
						mui('#txt-msg')[0].disabled = true;
						mui('#btn-file')[0].style.disabled = true;

						var subhomePage = plus.webview.getWebviewById('tab-webview-subhome.html');
						if(subhomePage) {
							mui.fire(subhomePage, 'myfresh');
						}

						var sublivePage = plus.webview.getWebviewById('tab-webview-sublive.html');
						if(sublivePage) {
							mui.fire(sublivePage, 'myfresh');
						}

						IM.noticeIm(); //结束会议通知IM
						location.reload();
					} else {
						mui.toast(r.errMsg);
					}
				}, function() {
					mui.toast('操作失败,请稍后重试');
				})
			}
		}, 'div');
	});

	// 加载会议
	loadMeeting(meetingid, userid, Video.init, function(status) {
		if(status != 4) {
			IM.init(token, meetingid, userid); // 初始化IM
		}
	});

	loadMeetingMsg(meetingid, offset, limit);

	$(document).on('click', '#detailFiles li', function() {
		var path = $(this).attr('data-path');
		var name = $(this).attr('data-name');
		mui.confirm('确认下载资料?', '下载提示', '', function(type) {
			if(type.index == '1') {
				var down = plus.downloader.createDownload(path, {
					filename: '_downloads/' + name
				}, function(d, status) {
					if(status == 200) {
						plus.runtime.openFile(d.filename);
						return;
					}
					mui.toast('下载失败' + status);
				});
				down.start();
			}
		}, 'div');
	});

});

// 查看历史记录
mui('body').on('tap', '#chat-msg .showmore', function() {
	var meetingid = $(this).attr('data-meetingid');
	var offset = $(this).attr('data-offset');
	var limit = $(this).attr('data-limit');

	$(this).remove();
	if(totals != 0) {
		if(totals >= offset) {
			loadMeetingMsg(meetingid, offset, limit, 1);
		} else {
			$(this).remove();
			mui.toast('暂无更多数据')
		}
	} else {
		mui.toast('暂无历史数据');
	}
})